package com.aaa.aoplo4j;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;

/**
 * @author ：刘涛
 * @date ：Created in 2020/12/2 20:09
 * @description：aop切面日志
 * @modified By：
 * @version: 1.0
 */

/*把当前类标识为一个切面供容器读取*/
@Aspect
/*将这个类交给spring管理*/
@Component
/*日志打印注解*/
@Slf4j
public class AOPLog {

    private long start = 0;
    /**
     * 切入点
     */
    @Pointcut("execution(* com.aaa.controller.*.*(..))")
    public void pointcut(){}

    /**
     * 通知
     */
    @Before("pointcut()")
    public void before(JoinPoint point){

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        /*获取请求*/
        HttpServletRequest request = requestAttributes.getRequest();
        /*获取响应*/
        HttpServletResponse response = requestAttributes.getResponse();
        /*获取请求地址*/
        String addr = request.getRemoteAddr();
        /*获取请求路径*/
        String uri = request.getRequestURI();
        /*获取请求参数*/
        Object[] args = point.getArgs();
        /*获取开始时间*/
        start = System.currentTimeMillis();
        /*打印日志信息*/
        log.info("=========请求地址是========"+addr);
        log.info("=========请求路径是========"+uri);
        log.info("=========请求参数是========"+ Arrays.toString(args));
    }

    @After("pointcut()")
    public void after(){
        /*耗时多少（秒）*/
        long end = System.currentTimeMillis();
        log.info("=================耗时================="+ ((end-start)/1000));
        log.info("=================结束了=================");
    }
}
